package com.zondy.mapgis.android.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.MeasureSpec;

public class BitmapUtils
{

	/**
	 * view转化为Bitmap
	 */
	public static Bitmap convertViewToBitmap(View view)
	{
		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		return bitmap;
	}


	/**
	 * bitmap转二进制
	 * 
	 * @param bitmap
	 * @return
	 */
	public static byte[] Bitmap2Bytes(Bitmap bitmap)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * bitmap转二进制
	 * 
	 * @param byetes
	 * @return
	 */
	public static Bitmap Bytes2Bimap(byte[] byetes)
	{
		if (byetes.length != 0)
		{
			return BitmapFactory.decodeByteArray(byetes, 0, byetes.length);
		}
		else
		{
			return null;
		}
	}

	/**
	 * 读文件的得到文件字节流
	 * 
	 * @param filePath
	 * @return
	 */
	public static byte[] readFileToBytes(String filePath)
	{
		byte[] bytes = null;
		try
		{
			BufferedInputStream bi = new BufferedInputStream(new FileInputStream(filePath));
			// 输入流转字节流
			bytes = new byte[bi.available()];
			bi.read(bytes);
			bi.close();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bytes;

	}

	/**
	 * 把字节流放到本地
	 * 
	 * @param bytes
	 * @param filePath
	 * @throws IOException
	 */
	public static void writeBytesFile(byte[] bytes, String filePath) throws IOException
	{
		try
		{
			BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(filePath));
			bo.write(bytes);
			bo.flush();
			bo.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}


	/**
	 * 输入流转字节流
	 * */
	public static byte[] InputStreamToByte(InputStream is) throws IOException
	{
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int ch;
		while ((ch = is.read(buffer)) != -1)
		{
			bytestream.write(buffer, 0, ch);
		}
		byte data[] = bytestream.toByteArray();
		bytestream.close();
		return data;
	}

}
